﻿using System;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using System.Web.Routing;
using Lilium;

namespace Lilium.Web.Mvc
{
	public class UnityControllerFactory : DefaultControllerFactory
	{
		public UnityControllerFactory(IContainerProvider containerProvider)
		{
			if (containerProvider == null) throw new ArgumentNullException("containerProvider");

			m_ContainerProvider = containerProvider;
		}

        protected override System.Web.Mvc.IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			var container = ContainerProvider.GetContainer();

			var controller = controllerType == null
				? base.GetControllerInstance(requestContext, controllerType)
                : (System.Web.Mvc.IController)container.Resolve(controllerType);

			var entityController = controller as EntityController;
			if (entityController != null)
				RegisterEntityController(container, entityController);

			return controller;
		}
        
        protected override Type GetControllerType(RequestContext requestContext, string controllerName)
        {
            return base.GetControllerType(requestContext, controllerName);
        }
        
		#region public IContainerProvider ContainerProvider

		private readonly IContainerProvider m_ContainerProvider;

		public IContainerProvider ContainerProvider
		{
			get
			{
				return m_ContainerProvider;
			}
		}

		#endregion

		private static void RegisterEntityController(IUnityContainer container, EntityController controller)
		{
			if (container == null) throw new ArgumentNullException("container");
			if (controller == null) throw new ArgumentNullException("controller");

			container.RegisterInstance<IServiceProvider>(controller);
			container.RegisterInstance<ControllerBase>(controller);
			container.RegisterInstance<Controller>(controller);
		}
	}
}